import React, {useEffect} from 'react';
import classes from './Cart.module.css'
import iconImg from '../../assets/bag.png'
import CartContext from "../../store/CartContext.jsx";
import CartDetails from "./cartDetails/CartDetails.jsx";
import Checkout from "./checkout/Checkout.jsx";
const Cart = () => {
    const ctx = React.useContext(CartContext)

    //控制详情是否显示
    const [showDetail,setShowDetail] = React.useState(false)

    //控制结账页是否显示
    const [showCheckout,setShowCheckout] = React.useState(false)

    //组件每次渲染时，检查商品总数量，如果为零，
    // 设置showDetail为false
    useEffect(() => {
        console.log('effect执行了')
        if(ctx.totalCount === 0){
            //隐藏购物车
            setShowDetail(false)
            //隐藏结账页
            setShowCheckout(false)
        }
    },[ctx.totalCount]);

    const showDetailHandler = () => {
        if(ctx.totalCount === 0 ){
            setShowDetail(false)
            return
        }


        setShowDetail(prev => !prev)
    }

    //结算页显示与关闭
    const showCheckoutHandler = () => {
        if(ctx.totalCount === 0) {
            return
        }
        setShowCheckout(prev => !prev)
    }

    return (
        <div className={classes.cart} onClick={showDetailHandler}>
            {/*结账页*/}
            {showCheckout && <Checkout onShowCheckout={setShowCheckout} />}
            {/*购物车详情*/}
            {showDetail && <CartDetails onShowDetail={showDetailHandler}/>}
            <div className={classes.icon}>
                <img src={iconImg} alt=''/>
                {ctx.totalCount === 0 ? null : <span className={classes.totalCount}>{ctx.totalCount}</span>}
            </div>
            {ctx.totalPrice === 0 ? <p className={classes.noMeal}>未选中商品</p>  : <p className={classes.price}>{ctx.totalPrice}</p>}
            <button
                onClick={showCheckoutHandler}
                className={`${classes.button} ${ctx.totalPrice === 0 ? classes.disabled : ''}`}>去结算</button>
        </div>
    );
};

export default Cart;
